<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="60%"
    :show-close="false"
    :append-to-body="true"
    class="mapDialog" :close-on-click-modal = "false">
    <span slot="title">
      地图
      <el-button size="mini" class="floatRight" @click="close">关闭</el-button>
    </span>
      <div class="inlineblock verticalmiddle infoitem" style="width: 80%;margin-bottom: 10px;">
        <div class="inlineblock verticalmiddle">
          位置
        </div>
        <div class="inlineblock verticalmiddle informationItem">
          <el-autocomplete  class="inline-input" size="mini"  v-model="searchLocation"  :fetch-suggestions="querySearch"
          placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
        </div>
      </div>
      <div id="container" class="mapWrap"></div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close" size="mini">取 消</el-button>
      <el-button type="primary" @click="determine" size="mini">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: 'mapComponent',
  props: {
    flagDialogShow: Boolean,
    mapMsg: Object
  },
  data () {
    return {
      dialogVisible: false,
      map: null,
      marker: null,
      type1OfReturn: {lngLat:null, address:''},
      searchLocation:"",
    }
  },
  watch: {
      flagDialogShow(val) {
        this.dialogVisible = this.flagDialogShow
        if (val) {
          this.init()
        }
      }
  },
  methods: {
    init () {
      // 创建地图，自动获取当前位置或已存在位置
      if(this.mapMsg.center && this.mapMsg.center != null){
        let tempPoint = [this.mapMsg.center.lng, this.mapMsg.center.lat]
        this.createMap(tempPoint)
      }else {
        this.createMap()
      }
    },
    // 查询位置
    querySearch(queryString, cb) {
      this.searchMap().then(res => {
        if(res.status == 1){
          var standardString = [];
          res.pois.forEach((item) =>{
            var obj = {};
            obj.value = item.name + "(" + item.cityname +")";
            obj.lanlat = item.location;
            standardString.push(obj)
          })
          var restaurants = standardString;
          var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          var results = []
          cb(results);
        }
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    searchMap(){
      return new Promise((resolve, reject) => {
        this.$jsonp("https://restapi.amap.com/v3/place/text",{
          keywords: this.searchLocation,
          key:'1f6c2cb374d4e3799846729fad7c7261'
        }).then(json=>{
          resolve(json)
        })
      })
    },
    // searchMap(){
    //   return new Promise((resolve, reject) => {
    //     this.$jsonp("https://uri.amap.com/search",{
    //       keyword: this.searchLocation,
    //       src: "mypage",
    //       key:'1f6c2cb374d4e3799846729fad7c7261'
    //     }).then(json=>{
    //       resolve(json)
    //     })
    //   })
    // },
    handleSelect(val){
      let arr = val.lanlat.split(",")
      // 把选中的点位放到中心
      var tempPoint = [arr[0],arr[1]]
      this.map.setCenter(tempPoint)
      this.createOneMark(tempPoint)
      this.type1OfReturn.lngLat = tempPoint
    },
    createMap(center) {
      AMapLoader.load({
        key: "f926b43598eca0f599b9de850e4eaa91", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [""], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          let obj  = {
            viewMode: '2D', //默认使用 2D 模式
            zoom: 12, //地图级别
          }
          if(center) {
            obj.center = center //地图中心点
          }
          this.map = new AMap.Map("container", obj);
          if(center) {
            // 添加点标记
            this.marker = new AMap.Marker({
              position: center, //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            });
            //将创建的点标记添加到已有的地图实例：
            this.map.add(this.marker);
          }
          // 创建地图点击事件
          this.map.on("click", this.clickMap);
        })
        .catch((err) => {
        });
    },
    // 点击地图之后的事件
    clickMap(event) {
      // 解析经纬度得到详细address，用于展示
      let lngLat = [event.lnglat.lng, event.lnglat.lat]
      this.createOneMark(lngLat)
      this.type1OfReturn.lngLat = lngLat
    },
    createOneMark (center) {
      // 清空之前的所有点
      if (this.marker) {
        this.marker.setMap(null);
        this.marker = null;
      }
      // 添加点标记
      this.marker = new AMap.Marker({
        position: center, //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      });
      //将点标记添加到已有的地图
      this.marker.setMap(this.map);
    },
    close() {
      this.searchLocation = "";
      this.$emit('update:flagDialogShow', false)
    },
    determine () {
      switch (this.mapMsg.type) {
        case 1:
          this.$emit('getLnglat', this.type1OfReturn.lngLat)
          break
      }
      this.close()
    }
  }
}
</script>

<style >
  .mapDialog .el-dialog .el-dialog__body {
      padding: 10px;
      height: calc(100% - 85px);
      overflow-y: auto;
      width:100%;
  }
  .mapDialog .el-dialog{
    margin-top: 10vh !important;
    height: 70% !important;
  }
  .mapDialog .mapWrap{
    width: 100%;
    height: calc(100% - 50px);
  }
  .mapDialog .floatRight{
    float: right;
  }

</style>
